import React, { useEffect } from 'react';
import { useMutation, useApolloClient } from '@apollo/client';

import UserForm from '../components/UserForm';
import { SIGNUP_USER } from '../gql/mutation';

//加上传给组件的props，以备后用
const SignUp = props => {
    useEffect(() => {
        document.title = 'Sign Up —— Notedly';
    });

    //Apollo Client
    const client = useApolloClient();
    //添加变更操作钩子
    const [ signUp, { loading, error }] = useMutation(SIGNUP_USER, {
        onCompleted: data => {
            //把JWT存储的LocalStorage中
            localStorage.setItem('token', data.signUp);
            //更新本地缓存
            client.writeData({ data: { isLoggedIn: true } });
            //把用户重定向到首页
            props.history.push('/');
        }
    });

    return(
        <React.Fragment>
            <UserForm action={signUp} formType="signup"></UserForm>
            {loading && <p>Loading...</p>}
            {error && <p>Error creating an account!</p>}
        </React.Fragment>
    )
};

export default SignUp;